<template>
  <div class="pc-bg" :style="{ backgroundImage: `url(${bg})` }">
    <div class="pc-logo" :style="{ backgroundImage: `url(${logo})` }"></div>
    <div class="pc-form-wrap">
      <div class="pc-form" v-if="state.dataList && state.dataList.length > 0">
        <!-- <div class="pc-form-total">
          <div>总题数</div>
          <div>共{{ dataList.length }}道题</div>
        </div> -->
        <div class="pc-form-time">
          <div>剩余时间</div>
          <div>{{ formatTime(time) }}</div>
        </div>
        <!-- <div class="pc-form-head">
          <span>第</span>
          <span>{{ index + 1 }}</span>
          <span>题</span>
        </div> -->
        <div class="pc-form-title">{{ (index + 1) + '、' + state.dataList[index].question_title }}</div>
        <div class="pc-form-bd">
          <template v-if="!state.dataList[index].answer_flag">
            <div class="pc-form-question"
              v-for="(item, idx) in state.dataList[index].answersList"
              :key="idx"
              @click="chooseOptions(idx)"
            >
              <van-icon name="circle" size="40" />
              <span class="question-text">{{ item }}</span>
            </div>
          </template>
          <template v-else>
            <div class="pc-form-question"
              v-for="(item, i) in state.dataList[index].answersList"
              :key="i"
            >
              <template v-if="state.answerList[index] === 'right'">
                <template v-if="isRightOrWrong(i, 'right')">
                  <van-icon name="passed" size="40" color="#08f76d" />
                  <span class="question-text color-green">{{ item }}</span>
                </template>
                <template v-else>
                  <van-icon name="circle" size="40" />
                  <span class="question-text">{{ item }}</span>
                </template>
              </template>
              <template v-if="state.answerList[index] === 'wrong'">
                <template v-if="isRightOrWrong(i, 'wrong')">
                  <van-icon name="close" size="40" color="#FF4444" />
                  <span class="question-text color-red">{{ item }}</span>
                </template>
                <template v-else>
                  <van-icon name="circle" size="40" />
                  <span class="question-text">{{ item }}</span>
                </template>
              </template>
            </div>
          </template>
        </div>

        <!-- <div class="exam-answer" v-if="state.dataList[state.idx].answer_flag">
          <p>答案:</p>
          <p>
            正确答案 <span class="color-blue">{{formatAnswer(state.dataList[state.idx].answer_id)}}</span>，
            你的答案 <span class="color-red">{{formatAnswer(state.dataList[state.idx].answer_content)}}</span>。
            <span v-if="state.answerList[state.idx] === 'right'">恭喜你，答对了！</span>
            <span v-else>很遗憾，答错了！</span>
          </p>
        </div> -->

        <div class="pc-form-bottom" v-if="state.dataList[index].answer_flag">
          <p>答案: <span class="color-green">{{formatAnswer(state.dataList[index].answer_id)}}</span>。
            <span v-if="state.answerList[index] === 'right'">恭喜你，答对了！</span>
            <span v-else>很遗憾，答错了！</span>
          </p>
        </div>
      </div>
      <div class="pc-form-foot">
        <div class="pc-form-foot-item">
          <EButton type="red" :src="require('../../assets/images/jiaojuan.png')" @click="submit()"></EButton>
        </div>
        <div class="pc-form-foot-item">
          <EButton :src="require('../../assets/images/befo.png')" @click="prev()"></EButton>
        </div>
        <div class="pc-form-foot-item">
          <EButton :src="require('../../assets/images/next.png')" @click="next()"></EButton>
        </div>
      </div>

      <div class="question-list">
        <div class="pc-form-box">
          <template v-for="(item, i) in state.answerList" :key="i" >

            <template v-if="state.answerList[i] === 'right'">
                <!-- <div class="icon-circle bg-blue" :class="{'border': state.idx === i}" @click="chooseQuestion(i)">
                  {{i + 1}}
                </div> -->
                <span class="bg-green" :class="{'border': index === i}" @click="index = i">{{ i + 1 }}</span>
              </template>
              <template v-else-if="state.answerList[i] === 'wrong'">
                <!-- <div class="icon-circle bg-red" :class="{'border': state.idx === i}" @click="chooseQuestion(i)">
                  {{i + 1}}
                </div> -->
                <span class="bg-red" :class="{'border': index === i}" @click="index = i">{{ i + 1 }}</span>
              </template>
              <template v-else>
                <span :class="{'active': index === i}" @click="index = i">{{ i + 1 }}</span>
              </template>

          </template>
        </div>
      </div>

    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
// import dataList from '../../mock/index'
import { useRoute, useRouter } from 'vue-router'
import { toast } from '@/components/Toast/index'
import { getDataList, submitFormPc } from '@/api'
import { ItemData, AnswerJsonItem } from '@/interface/api'
import debounce from 'lodash.debounce'
import { Dialog } from 'vant'

// const idxToString = ['A', 'B', 'C', 'D', 'E', 'F']
const route = useRoute()
const router = useRouter()
const optionTitle = ['A', 'B', 'C', 'D', 'E', 'F'] // 字母数组
const index = ref(0)
// const total = ref(0)
const time = ref(15 * 60)
// const time = ref(10)
const flag = ref(false)

const bg = ref('')
const logo = ref('')
const timeControll = ref()
const state = reactive({
  dataList: [] as ItemData[],
  answerList: [] as string[],
  rightCount: 0,
  wrongCount: 0
})
const classicId = ref('')

onMounted(() => {
  classicId.value = route.query.classicId as string
  const systemInfo = window.localStorage.systemInfo
  if (systemInfo) {
    const systemInfoObj = JSON.parse(systemInfo)
    bg.value = systemInfoObj.bg_img
    logo.value = systemInfoObj.logo
  }
  if (classicId.value) {
    initData()
    startTime()
  } else {
    toast('没有获取到科目')
  }
})

onBeforeUnmount(() => {
  clearInterval(timeControll.value)
})

const initData = async () => {
  try {
    const res: any = await getDataList({
      group: 'pc',
      type_id: classicId.value
    })
    console.log('question', res)
    const dataList = res.data
    if (dataList && dataList.length > 0) {
      dataList.map((item: ItemData) => {
        item.answer_content = ''
        item.answersList = item.answers.split(',')
        return item
      })
      // 增加一个题目列表数组，存储回答的正确与否
      if (dataList && dataList.length > 0) {
        const answerList = new Array(dataList.length)
        state.answerList = answerList
      }
      state.dataList = dataList
    } else {
      toast('题库中暂时没有题目')
    }
  } catch (err) {
    toast('网络连接不可用，请稍后重试')
  }
}

const startTime = () => {
  flag.value = true
  timeControll.value = setInterval(() => {
    console.log(time.value)
    if (time.value > 0) {
      time.value -= 1
      if (time.value === 2) {
        toast('时间到了, 自动交卷！')
      }
    } else {
      clearInterval(timeControll.value)
      // 交卷
      submitAnswer()
    }
  }, 1000)
}

const formatTime = (time: number) => {
  return `${Math.floor(time / 60)}分${(time % 60)}秒`
}

const prev = () => {
  if (index.value === 0) {
    toast('这是第一题！')
  }
  if (index.value > 0) {
    index.value -= 1
  }
}

const next = () => {
  if (index.value < state.dataList.length - 1) {
    index.value += 1
  } else if (index.value === state.dataList.length - 1) {
    // index.value = 0
    toast('最后一题了！')
  }
}

const formatAnswer = (arr: string) => {
  const idx = index.value
  const type = state.dataList[idx].answer_type
  if (type === '3') {
    const tempArr = (arr as string).split(',')
    const answerString = tempArr.map((item: any) => {
      return optionTitle[item]
    }).join('、')
    return `【${answerString}】`
  } else {
    return optionTitle[Number.parseInt(arr)]
  }
}

// 单选和多选 点击选择项
const chooseOptions = (i: number) => {
  const idx = index.value
  // const type = state.dataList[idx].answer_type
  state.dataList[idx].answer_content = i.toString()
  // // 显示提交按钮
  // state.showQuestionBtn = true
  state.dataList[idx].answer_flag = 'true'
  setAnswerList()
}

// 设置答题集合
const setAnswerList = () => {
  const idx = index.value
  const type = state.dataList[idx].answer_type
  if (type === '3') {
    const answerId = state.dataList[idx].answer_id
    const answerContent = state.dataList[idx].answer_content
    let temp = 'right'
    if (answerId.length === answerContent.length) {
      for (let i = 0; i < answerId.length; i++) {
        if (!answerId.includes(answerContent[i])) {
          temp = 'wrong'
        }
      }
    } else {
      temp = 'wrong'
    }
    state.answerList[idx] = temp
    if (temp === 'right') {
      state.rightCount = state.rightCount + 1
    } else {
      state.wrongCount = state.wrongCount + 1
    }
  } else {
    const answerId = state.dataList[idx].answer_id
    const answerContent = state.dataList[idx].answer_content.toString()
    state.answerList[idx] = answerId === answerContent ? 'right' : 'wrong'
    if (state.answerList[idx] === 'right') {
      state.rightCount = state.rightCount + 1
    } else {
      state.wrongCount = state.wrongCount + 1
    }
  }
}

// 判断答题是否是对的
const isRightOrWrong = (i: number, type: string) => {
  const idx = index.value
  const answer = type === 'right' ? state.dataList[idx].answer_id : state.dataList[idx].answer_content
  return answer.indexOf(i.toString()) > -1
}

const submit = debounce(function () {
  Dialog.confirm({
    title: '提示',
    message: '您确定要交卷吗？',
    confirmButtonColor: '#1b79f0'
  }).then(() => {
    submitAnswer()
  })
}, 500)

const submitAnswer = async () => {
  const answer = getSubmitanswer()
  const params = {
    type_id: classicId.value,
    score: state.rightCount * 5,
    answer,
    use_times: 15 * 60 - time.value
  }
  try {
    const { data } = await submitFormPc(params)
    window.sessionStorage.practice = JSON.stringify({
      rightCount: state.rightCount,
      wrongCount: state.wrongCount,
      count: state.dataList.length,
      remote_auth_server_url: data && data.remote_auth_server_url,
      username: data && data.username,
      password: data && data.password
    })
    router.replace('/pc-success')
  } catch (err) {
    toast((err as Error).message)
  }
}

// 处理需要上传的答题数据
const getSubmitanswer = () => {
  const answerJson: AnswerJsonItem[] = []
  state.dataList.forEach((item) => {
    answerJson.push({
      id: item.id,
      answer: item.answer_content
    })
  })
  // console.log(JSON.stringify(answerJson).length)
  return JSON.stringify(answerJson)
}
</script>

<style lang="less" scoped>
  .pc-bg {
    width: 1920px;
    height: 1080px;
    background-color: #c8c7c7;
    position: relative;
    background-size: cover;
  }

  .pc-logo {
    position: absolute;
    top: 20px;
    left: 20px;
    width: 300px;
    height: 150px;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    z-index: 99;
  }

  .pc-form {
    width: 1200px;
    height: 600px;
    background-color: #1b79f0;
    padding: 40px 120px;
    border-radius: 10px;
    box-sizing: border-box;
    position: relative;
  }
  .question-list {
    margin-top: 40px;
    width: 1200px;
    padding: 20px 0 0;
    background-color: #1b79f0;
    border-radius: 10px;
  }
  .pc-form-wrap {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .pc-form-foot {
    position: relative;
    display: flex;
    margin-top: 40px;
    margin-bottom: 40px;
  }
  .pc-form-foot-item {
    flex: 1;
    text-align: center;
  }

  .pc-form-total {
    width: 120px;
    position: absolute;
    top: 20px;
    left: 20px;
    text-align: center;
    font-size: 24px;
    color: #FFF700;
    font-weight: bolder;
  }
  .pc-form-time {
    width: 150px;
    position: absolute;
    bottom: 15px;
    right: 0px;
    text-align: center;
    font-size: 24px;
    color: #FFF700;
    font-weight: bolder;
  }
  .pc-form-box {
    // padding: 60px 0 0px;
    text-align: center;
    color: #fff;
    max-width: 670px;
    margin: 0 auto;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    span {
      border: 1px solid white;
      width: 55px;
      display: inline-block;
      height: 55px;
      line-height: 55px;
      font-size: 30px;
      text-align: center;
      margin: 0 5px 20px;
      &.active {
        color: #1b79f0;
        background-color: rgba(242, 243, 245, .9);
      }
    }
  }
  .pc-form-title {
    color: white;
    font-size: 28px;
    position: relative;
    margin-bottom: 30px;
  }
  .pc-form-bottom {
    padding-top: 20px;
    color: #fff;
    font-size: 24px;
  }
  .pc-form-question {
    color: white;
    display: block;
    font-size: 28px;
    position: relative;
    user-select: none;
    height: 80px;
    display: flex;
    align-items: center;
  }
  .question-text {
    margin-left: 20px;
  }
  .color-red {
    color: #FF4444;
  }
  .color-green {
    color: #08f76d;
  }
  &.bg-green {
    color: #08f76d;
    border:1px solid rgba(222,255,238,1);
    background-color: rgba(222,255,238,1);
    &.border {
      border:1px solid #08f76d;
    }
  }
  &.bg-red {
    color: #FF4444;
    border:1px solid rgb(253, 226, 226);
    background-color: rgb(253, 226, 226);
    &.border {
      border:1px solid #FF4444;
    }
  }
</style>
